var express = require('express');
var router = express.Router();
var path = require('path')
var fs = require('fs')
var Result = require('../../utils/api')
//上传图片的模板
var multer = require('multer');
//生成的图片放入uploads文件夹下
var upload = multer({
    dest: 'public/uploads/'
})
var checkAuth = require('../../utils/checkAuth')
//图片上传必须用post方法
router.post('/img', checkAuth, upload.single('file'), (req, res) => {
    fs.readFile(req.file.path, (err, data) => {
        if (err) return res.send({
            msg: '上传失败'
        })
        // 保证文件名字唯一性
        let time = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
        let extname = req.file.mimetype.split('/')[1]
        let keepname = time + '.' + extname
        console.log(path.join(__dirname, '../../public/uploads/' + keepname));
        fs.writeFile(path.join(__dirname, '../../public/uploads/' + keepname), data, (err) => {
            if (err) return res.send({
                msg: '写入失败'
            })
            res.send({
                err: 0,
                msg: '上传完成',
                src: '/uploads/' + keepname
            })
        })
    })
})

module.exports = router;